package com.alibaba.cloud.transmit.mq;

import com.alibaba.cloud.transmit.constant.TransmitConstant;
import com.alibaba.cloud.transmit.constant.TransmitEnum;
import com.alibaba.cloud.transmit.dao.TransmitDetailsMapper;
import com.alibaba.cloud.transmit.dao.TransmitMapper;
import com.alibaba.cloud.transmit.entity.TransmitData;
import com.alibaba.cloud.transmit.entity.TransmitDataDTO;
import com.alibaba.cloud.transmit.entity.TransmitDataDetails;
import com.alibaba.fastjson.JSON;
import com.alibaba.framework.utils.UUIDUtil;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.Date;
import java.util.Objects;

@Component
public class TransmitListener {

    private static final Logger LOGGER = LoggerFactory.getLogger(TransmitListener.class);

    @Autowired
    private TransmitMapper transmitMapper;

    @Autowired
    private TransmitDetailsMapper transmitDetailsMapper;

    @Transactional(rollbackFor = Exception.class)
    @RabbitListener(queues = TransmitConstant.TRANSMIT_QUEUE)
    public void receiveData (Message message, Channel channel) throws IOException {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        Date date = new Date();

        String data = new String(message.getBody());
        TransmitDataDTO transmitDataDTO = JSON.parseObject(data, TransmitDataDTO.class);
        if (Objects.isNull(transmitDataDTO)) {
            return;
        }

        // 上传数据
        TransmitDataDetails transmitDataDetails = new TransmitDataDetails();
        String detailsId = UUIDUtil.uuid();
        BeanUtils.copyProperties(transmitDataDTO, transmitDataDetails);
        transmitDataDetails.setCreateTime(date);
        transmitDataDetails.setId(detailsId);
        transmitDetailsMapper.insert(transmitDataDetails);


        TransmitData transmitData = new TransmitData();
        BeanUtils.copyProperties(transmitDataDTO, transmitData);
        transmitData.setTransStatus(TransmitEnum.TRANSMIT_STATUS.SUCCESS.getValue());
        transmitData.setCreateTime(date);
        transmitData.setTransDetailsId(detailsId);
        transmitMapper.insert(transmitData);
        LOGGER.info("数据上传成功：{}", transmitData);

        try {
            channel.basicAck(deliveryTag, false);
        } catch (IOException e) {
            e.printStackTrace();
            channel.basicNack(deliveryTag, false, false);
        }
    }
}
